// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AgentLocatorTests.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Test.Robotics.Runtime
{
    using System;
    using System.Collections.Generic;
    using Microsoft.Robotics.IO;
    using Microsoft.Robotics.Runtime;
    using Microsoft.Robotics.Visualization;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// Agent Locator Basic Unit Tests
    /// </summary>
    [TestClass]
    public class AgentLocatorTests
    {
        /// <summary>
        /// Path to the test manifest
        /// </summary>
        private const string TestManifestPath = "TestManifest.xml";

        /// <summary>
        /// Name of the test agent
        /// </summary>
        private const string TestAgentName = "TestAgent";

        /// <summary>
        /// Test GetAgent when agent does not exist
        /// </summary>
        [TestMethod]
        [TestCategory("Unit")]
        [Priority(0)]
        [ExpectedException(typeof(InvalidOperationException))]
        public void GetAgentNotFound()
        {
            AgentLocator locator = new AgentLocator();
            try
            {
                // first create and load a test manifest
                Manifest manifest = this.CreateTestManifest();
                Serializer.Save(TestManifestPath, manifest, manifest.GetKnownTypes());
                locator.LoadFrom(TestManifestPath);

                // verify the valid agent name is registered
                var timerAgent = locator.GetAgent(TestAgentName);
            }
            catch (Exception e)
            {
                // We want to make sure that if any of calls above throws InvalidOperationException
                // which they may for various reasons - we dont confuse those exceptions with the one
                // that deactivate must throw
                throw new Exception("Unexpected exception thrown", e);
            }

            // now verify the failure case.  Should throw.
            var nonExistentAgent = locator.GetAgent("notValidAgentName");
        }

        /// <summary>
        /// Test when agent is already registered and try to register one with same name
        /// </summary>
        [TestMethod]
        [TestCategory("Unit")]
        [Priority(0)]
        [ExpectedException(typeof(InvalidOperationException))]
        public void AgentAlreadyRegistered()
        {
            AgentLocator locator = new AgentLocator();

            try
            {
                locator.Register(new CodeCoverageAgent(TestAgentName));
            }
            catch (Exception e)
            {
                // We want to make sure that if any of calls above throws InvalidOperationException
                // which they may for various reasons - we dont confuse those exceptions with the one
                // that deactivate must throw
                throw new Exception("Unexpected exception thrown", e);
            }

            // this shoud throw
            locator.Register(new CodeCoverageAgent(TestAgentName));
        }

        /// <summary>
        /// Test when network proxy is already registered and try to register one with same name
        /// </summary>
        [TestMethod]
        [TestCategory("Unit")]
        [Priority(0)]
        [ExpectedException(typeof(InvalidOperationException))]
        public void ProxyAlreadyRegistered()
        {
            AgentLocator locator = new AgentLocator();
            UdpFarProxy proxy2;

            try
            {
                UdpFarProxy proxy = new UdpFarProxy(this.CreateTestNetworkProxyDefinition("Proxy", "producer"), locator);
                locator.RegisterProxy(proxy);
                proxy2 = new UdpFarProxy(this.CreateTestNetworkProxyDefinition("Proxy", "producer"), locator);
            }
            catch (Exception e)
            {
                // We want to make sure that if any of calls above throws InvalidOperationException
                // which they may for various reasons - we dont confuse those exceptions with the one
                // that deactivate must throw
                throw new Exception("Unexpected exception thrown", e);
            }

            Assert.IsNotNull(proxy2);

            // this shoud throw
            locator.RegisterProxy(proxy2);
        }

        /// <summary>
        /// Creates a test manifest on disk by serializing a simple manifest
        /// </summary>
        /// <returns>The created manifest</returns>
        private Manifest CreateTestManifest()
        {
            Manifest manifest = new Manifest();
            
            CodeCoverageAgent agent = new CodeCoverageAgent(TestAgentName);
            manifest.Agents.Add(agent);

            ProxyDefinition proxy1 = this.CreateTestProxyDefinition("Proxy");
            manifest.RemoteAgentProxies.Add(proxy1); 
            
            ProxyDefinition proxy2 = this.CreateTestNetworkProxyDefinition("NetworkProxy", TestAgentName);
            manifest.NetworkEnabledAgentProxies.Add(proxy2);

            return manifest;
        }

        /// <summary>
        /// Creates a test network enabled proxy
        /// </summary>
        /// <param name="proxyName">The proxy name</param>
        /// <param name="producerName">The producer name</param>
        /// <returns>A proxy definition</returns>
        private ProxyDefinition CreateTestNetworkProxyDefinition(string proxyName, string producerName)
        {
            return ProxyDefinition.CreateNetworkEnabledProxy(
                name: proxyName,
                producer: producerName,
                address: Environment.MachineName,
                publishContracts: new[] { typeof(AgentMessage) },
                publishNetworkPortNumber: 0,
                controlContracts: null,
                controlNetworkPortNumber: 0);
        }

        /// <summary>
        /// Creates a test remote proxy
        /// </summary>
        /// <param name="name">The proxy name</param>
        /// <returns>A proxy definition</returns>
        private ProxyDefinition CreateTestProxyDefinition(string name)
        {
                return ProxyDefinition.CreateRemoteProxy(
                name: name,
                address: Environment.MachineName,
                publishContracts: new[] { typeof(AgentMessage) },
                publishNetworkPortNumber: 50001,
                controlContracts: null,
                controlNetworkPortNumber: 0);
        }
    }
}
